<?php

if(!defined('IN_WEBSHOP')) {
    exit('Access Denied');
}

class cart {

    var $sortCount;       //Ʒ
    var $totalCost;       //Ʒܽ 产品总额
    var $totalCost2;      //Ʒܽ 产品总额＋VAT＋运费等
	var $pay_amount;	  //支付总金额

    var $myCart;
    var $promoter_id;     // ǷPromoter ID5%ۿ value 1|0
	var $promoter_osd;	  // promoter 's outstanding commission
    var $country;         // ʹص

    var $discount;        // ȥۿ 折扣总额
    var $addvat;          // ˰	VAT总额
    var $addshippingfee;  // ˷  运费总额

    var $shipping_fee_ary; // ݿ`med_shipping`õ˷
	var $proTotalCost; //product 's cost; 产品总成本

    // ?
    function cart() {
        global $db;
        if ($db == null || $db == '') {
            die("db error");
        }

        $this->sortCount = 0;
        $this->totalCost = 0; //ԭ
        $this->totalCost2 = 0;  //ȥۿۣ˰գ ʷѺ֧۸
		$this->pay_amount = 0;
		$this->proTotalCost= 0;
		
        $this->discount = 0;
        $this->addvat = 0;
        $this->addshippingfee = 0;
		$this->courstFeeSum = 0;
        //ȡͬ˷
        $sql = "SELECT `weight`, `da_fee`, `eu_fee`, `other_fee` FROM `med_shipping` ORDER BY `weight` ASC";
        $query = $db->query($sql);
        while($rs = $db->fetch_array($query)) {
            // $COUNTRY_ARY ĹҶӦ
            $this->shipping_fee_ary[0][$rs['weight']] = $rs['da_fee'];
            $this->shipping_fee_ary[1][$rs['weight']] = $rs['eu_fee'];
            $this->shipping_fee_ary[2][$rs['weight']] = $rs['other_fee'];
        }
		$this->shipping_fee_ary[3]["0"] = 0;//'Pick up' return shipping 0

        if(!session_is_registered("myCart")) {
            session_register('myCart');
        }
        if(!session_is_registered("myCart_promoter_id")) {
            $_SESSION["myCart_promoter_id"] = 0;
        }
        if(!session_is_registered("myCart_country")) {
            $_SESSION["myCart_country"] = 0;
        }
		if(!session_is_registered("myCart_promoter_osd")) {
            $_SESSION["myCart_promoter_osd"] = 0;
        }
		
        $this->myCart = $_SESSION["myCart"];
        $this->promoter_id = $_SESSION["myCart_promoter_id"];
		$this->promoter_osd = $_SESSION["myCart_promoter_osd"];
        $this->country = intval($_SESSION["myCart_country"]);
		$this->signdate=$_SESSION["myCart_signdate"];
		
        $this->update();
    }

    // privatesessionֵӦ
    function update() {

        $myCart = $this->myCart;

        if(false==$myCart) {
            $this->sortCount = 0;
            $this->totalCost = 0;
            $this->totalCost2 = 0;
			$this->proTotalCost= 0;
			
            $this->myCart = array();
            $this->promoter_id = 0;     // ۿۣ5%
			$this->promoter_osd=0;
            $this->country = 0;         // Ͷݹңʷ

            $this->discount = 0;
            $this->addvat = 0;
            $this->addshippingfee = 0;
			$this->pay_amount = 0;

            return false;
        }

        //õƷ
        $this->sortCount=count($myCart);

        if($this->sortCount>0) {
            //ʼƷĽ
            $totalCost = 0;
            $sortCount = 0;

            $totalCost2 = 0;

            $discount = 0;
            $addvat = 0;
			$courseVat = 1; //vat值
            $addshippingfee = 0;
			$proTotalCost=0;
			$courseFeeSum = 0; //课程总费用

            foreach($myCart as $key=>$val) {
                if ($val['type'] == 'Courses / Programs') { //ѡγʱ
					$courseFeeSum += $val["old_price"]*$val["count"];
					$val["price"] = $myCart[$key]["old_price"];	
					if ($val['vat'] > 0) {	$courseVat = $val['vat']/100;}			
                }

                //,2λЧ格式化数字
                foreach($val as $proName=>$proVal) {
                    if($proName == "price" || $proName == "old_price") {
                        $val[$proName] = number_format(round(eregi_replace(",", "",$proVal),2), 2, '.', '');
                        $myCart[$key][$proName] = $val[$proName];
                    }
                }
				$myCart[$key]["cost"] = number_format(round($val["count"]*$val["old_price"], 2), 2, '.', '');
				$myCart[$key]["cost2"] = $myCart[$key]["cost"];
 

               // ÿƷ˰
                if ($val['vat'] > 0) {
                    $addvat += $myCart[$key]["cost2"]*$val['vat']/100;
                }

                // Ʒ
                if ($val['productinfo']['weight'] > 0) {
                    $total_w += $val['productinfo']['weight']*$val['count'];
                }
				//product cost
                if ($val['productinfo']['cost'] >= 0) {
                    $proTotalCost += $val['productinfo']['cost']*$val["count"];
                }

                //õƷĽ
                $totalCost += $myCart[$key]["cost"];
                $sortCount+=1;

            }
            // Ʒʷ
            $addshippingfee = $this->getShippingFee($total_w);
			
			// 如果课程的总费用大于两倍佣金总额，则折扣等于佣金数，
			// 如果课程的总费用小于等于两倍佣金，则折扣等于总费用的一半
			if($courseFeeSum > 0)
			{
				if($courseFeeSum <= $this->promoter_osd*2)
					$discount = $courseFeeSum / 2 ;
				else
					$discount = $this->promoter_osd;
			}
			//补回上面多扣掉的vat值，此购物车类允许每个产品有不同的VAT值
			$addvat = $addvat - $discount*$courseVat;

            $this->sortCount = $sortCount;
            $this->totalCost = number_format(round($totalCost, 2), 2, '.', '');

            $this->discount = number_format(round($discount, 2), 2, '.', '');
            $this->addvat = number_format(round($addvat, 2), 2, '.', '');
            $this->addshippingfee = number_format(round($addshippingfee, 2), 2, '.', '');

            $this->totalCost2 = $totalCost-$discount+$addvat+$addshippingfee;
            $this->pay_amount = $this->totalCost2-$this->promoter_osd;
			$this->totalCost2 = number_format(round($this->totalCost2, 2), 2, '.', '');
			$this->pay_amount = number_format(round($this->pay_amount, 2), 2, '.', '');
			$this->proTotalCost = number_format(round($proTotalCost, 2), 2, '.', '');
			
            $this->myCart = $myCart;
            $_SESSION["myCart"] = $this->myCart;
            $_SESSION["myCart_promoter_id"] = $this->promoter_id;
            $_SESSION["myCart_country"] = $this->country;
            //echo "<pre>";print_r($_SESSION);exit;
        }
    }

    // һƷ
    // жǷcartУУcountһƷ
    /*
    * addOne($pid, $name, $type, $price, $short_desc, $vat, $rs);
    * addOne($id, $aname, $atype, $aprice, $ashortdesc, $avat, $ars);
    * ͨƷУ$ars Ӧ ˷ѣ
    * γУ ¼γ̵ԭ۸
    */
    function addOne($id, $aname, $atype, $aprice, $ashortdesc, $avat, $ars)    {

        $myCart = $this->myCart;
        if (!isset($myCart[$id]['count'])) {
            $myCart[$id]['count'] = 0;
        }

        //ùﳵ?
        $myCart[$id]["name"]  = $aname;
        $myCart[$id]["shortdesc"]  = $ashortdesc;
        $myCart[$id]["price"] = $aprice;
        $myCart[$id]["old_price"] = $aprice;
        $myCart[$id]["type"] = $atype;     // Ʒcategory_idͨƷǿγ
        $myCart[$id]["vat"] = $avat;
        $myCart[$id]["productinfo"] = $ars;

        ++$myCart[$id]["count"];
        $this->myCart = $myCart;

        //һĳԱ
        $this->update();
    }


    // һƷĵ
    function updatePrice($id, $price) {
        if($price <=0)  return false;

        $myCart = $_SESSION["myCart"];
        if($myCart[$id]==true) {
            $myCart[$id]["price"]=$price;
            $_SESSION["myCart"] = $myCart;
            $this->update();
        }
    }

    // һƷ1
    function removeOne($id) {
        $count = $this->myCart[$id]["count"];
        if($count>0) {
            $this->modifyCount($id, --$count);
        }
    }

    //ıƷĸ,뵥ۣһ?
    function modifyCount($id, $ncount, $price=0) {
        if($ncount <= 0) return false;
        $myCart = $this->myCart;
        if($myCart[$id]==true) {
            $myCart[$id]["count"]=$ncount;

            //д뵥ۣһ?
            if($price >0 ) $myCart[$id]["price"]=$price;

            $this->myCart = $myCart;
            $this->update();
        }

    }


    //һƷ
    function emptyOne($i) {
        $myCart = $this->myCart;
        unset($myCart[$i]);
        if(count($myCart)==0) {
            $this->emptyAll();
        } else {
            $this->myCart = $myCart;
            $this->update();
        }
    }

    // еƷ
    function emptyAll() {
        $this->myCart = array();
        $this->update();

        session_unset($_SESSION["myCart"]);
        session_unset($_SESSION["myCart_promoter_id"]);
        session_unset($_SESSION["myCart_country"]);
        session_destroy();
        @cookie(session_name(), '', 0);
    }

    // չﳵее?
    function emptyCart() {
        $myCart = $this->myCart;

        if (!empty($myCart)) {
            foreach($myCart as $key=>$val) {
                unset($myCart[$key]);

            }
        }

        $this->sortCount = 0;
        $this->totalCost = 0;
        $this->myCart = $myCart;
        $this->update();
    }

    // йﳵ?
    function getData() {
        if(!empty($this->myCart)) {
            return $this->myCart;
        }else{
            return array();
        }
    }

    //ȡһƷϢarray('id','name','price','count','cost');
    function getOne($i) {
        $data = $this->myCart[$i];
        if(false==$data) return array();

        $data["id"] = $i;
        return $data;
    }

    //promoter_id
    function setPromoterId($p) {
        $p = intval($p);
        $p = $p>0 ? $p : 0;
        $this->promoter_id = $p;
        $_SESSION["myCart_promoter_id"] = $this->promoter_id;
    }
    //promoter_osd
    function setPromoterOsd($osd) {
        $osd = floatval($osd);
        $osd = $osd>0 ? $osd : 0;
        $this->promoter_osd = $osd;
        $_SESSION["myCart_promoter_osd"] = $this->promoter_osd;
    }
    //country
    function setCountry($c) {
        $this->country = intval($c);
        $_SESSION["myCart_country"] = $this->country;
    }

    //ȡܵƷ
    function getSortCount() {
        return $this->sortCount;
    }

    //ȡܵƷֵ
    function getTotalCost() {
        return $this->totalCost;
    }

    //ȡcountry
    function getCountry() {
        return $this->country;
    }

    //ȡpromoter_id
    function getPromoterId() {
        return $this->promoter_id>0 ? $this->promoter_id : "";
    }
	function getPromoterOsd() {
        return  $this->promoter_osd;
    }
    //ȡȥۿ
    function getDisCount() {
        return $this->discount;
    }

    //ȡӵ˰
    function getAddVat() {
        return $this->addvat;
    }

    //ȡӵ˷
    function getAddShippingFee() {
        return $this->addshippingfee;
    }

    //ȡ֧Ľ
    function getTotalCost2() {
        return $this->totalCost2;
    }

    // ȡƷ˷
    function getShippingFee($total_weight) {

        foreach ($this->shipping_fee_ary[$this->country] as $k=>$v) {
            $last = $this->shipping_fee_ary[$this->country][$k];
            if ($total_weight <= $k) {                
                return $this->shipping_fee_ary[$this->country][$k];
            }
        }
        
        return $last;
        //return 0;
    }
    function getProTotalCost() {
        return $this->proTotalCost;
    }
	function getPayAmount(){
		return $this->pay_amount;
	}
}
?>